package com.foodorder.service;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 外部API服务
 */
@Service
@Slf4j
public class ExternalApiService {
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    @Value("${api.external.amap.key:your-amap-api-key}")
    private String amapApiKey;
    
    @Value("${api.external.amap.url:https://restapi.amap.com/v3}")
    private String amapApiUrl;
    
    /**
     * 获取地理位置信息（高德地图API）
     */
    public Map<String, Object> getLocationInfo(double latitude, double longitude) {
        try {
            String url = amapApiUrl + "/geocode/regeo" +
                    "?key=" + amapApiKey +
                    "&location=" + longitude + "," + latitude +
                    "&poitype=&radius=1000&extensions=all&batch=false&roadlevel=0";
            
            // 如果API Key未配置，返回模拟数据
            if ("your-amap-api-key".equals(amapApiKey)) {
                return createMockLocationInfo(latitude, longitude);
            }
            
            Map<String, Object> response = restTemplate.getForObject(url, Map.class);
            log.info("获取地理位置信息成功: {}", response);
            return response;
            
        } catch (Exception e) {
            log.error("获取地理位置信息失败", e);
            // 返回模拟数据作为备用
            return createMockLocationInfo(latitude, longitude);
        }
    }
    
    /**
     * 计算两点间距离（高德地图API）
     */
    public Map<String, Object> calculateDistance(double fromLat, double fromLng, double toLat, double toLng) {
        try {
            String url = amapApiUrl + "/distance" +
                    "?key=" + amapApiKey +
                    "&origins=" + fromLng + "," + fromLat +
                    "&destination=" + toLng + "," + toLat +
                    "&type=1";
            
            // 如果API Key未配置，返回模拟数据
            if ("your-amap-api-key".equals(amapApiKey)) {
                return createMockDistanceInfo(fromLat, fromLng, toLat, toLng);
            }
            
            Map<String, Object> response = restTemplate.getForObject(url, Map.class);
            log.info("计算距离成功: {}", response);
            return response;
            
        } catch (Exception e) {
            log.error("计算距离失败", e);
            // 返回模拟数据作为备用
            return createMockDistanceInfo(fromLat, fromLng, toLat, toLng);
        }
    }
    
    /**
     * 发送短信验证码
     */
    public boolean sendSmsCode(String phoneNumber, String code) {
        try {
            // 这里应该调用真实的短信API
            // 由于需要配置短信服务，这里使用模拟实现
            log.info("模拟发送短信验证码: {} -> {}", phoneNumber, code);
            
            // 模拟发送成功
            return true;
            
        } catch (Exception e) {
            log.error("发送短信验证码失败", e);
            return false;
        }
    }
    
    /**
     * 获取天气信息
     */
    public Map<String, Object> getWeatherInfo(String city) {
        try {
            String url = amapApiUrl + "/weather/weatherInfo" +
                    "?key=" + amapApiKey +
                    "&city=" + city +
                    "&extensions=base";
            
            // 如果API Key未配置，返回模拟数据
            if ("your-amap-api-key".equals(amapApiKey)) {
                return createMockWeatherInfo(city);
            }
            
            Map<String, Object> response = restTemplate.getForObject(url, Map.class);
            log.info("获取天气信息成功: {}", response);
            return response;
            
        } catch (Exception e) {
            log.error("获取天气信息失败", e);
            // 返回模拟数据作为备用
            return createMockWeatherInfo(city);
        }
    }
    
    /**
     * 创建模拟地理位置信息
     */
    private Map<String, Object> createMockLocationInfo(double latitude, double longitude) {
        Map<String, Object> mockData = new HashMap<>();
        mockData.put("status", "1");
        mockData.put("info", "OK");
        
        Map<String, Object> regeocode = new HashMap<>();
        Map<String, Object> addressComponent = new HashMap<>();
        addressComponent.put("city", "北京市");
        addressComponent.put("district", "朝阳区");
        addressComponent.put("province", "北京市");
        addressComponent.put("street", "建国路");
        addressComponent.put("streetNumber", "88号");
        
        regeocode.put("formatted_address", "北京市朝阳区建国路88号附近");
        regeocode.put("addressComponent", addressComponent);
        
        mockData.put("regeocode", regeocode);
        
        log.info("使用模拟地理位置信息: lat={}, lng={}", latitude, longitude);
        return mockData;
    }
    
    /**
     * 创建模拟距离信息
     */
    private Map<String, Object> createMockDistanceInfo(double fromLat, double fromLng, double toLat, double toLng) {
        // 简单计算直线距离（米）
        double distance = calculateStraightDistance(fromLat, fromLng, toLat, toLng);
        
        Map<String, Object> mockData = new HashMap<>();
        mockData.put("status", "1");
        mockData.put("info", "OK");
        
        Map<String, Object> result = new HashMap<>();
        result.put("distance", String.valueOf((int) distance));
        result.put("duration", String.valueOf((int) (distance / 50))); // 假设配送速度50米/分钟
        
        mockData.put("results", new Object[]{result});
        
        log.info("使用模拟距离信息: {}米", (int) distance);
        return mockData;
    }
    
    /**
     * 创建模拟天气信息
     */
    private Map<String, Object> createMockWeatherInfo(String city) {
        Map<String, Object> mockData = new HashMap<>();
        mockData.put("status", "1");
        mockData.put("info", "OK");
        
        Map<String, Object> live = new HashMap<>();
        live.put("weather", "晴");
        live.put("temperature", "22");
        live.put("winddirection", "北");
        live.put("windpower", "3");
        live.put("humidity", "65");
        live.put("reporttime", "2023-12-15 14:30:00");
        
        mockData.put("lives", new Object[]{live});
        
        log.info("使用模拟天气信息: {}", city);
        return mockData;
    }
    
    /**
     * 计算两点间直线距离（米）
     */
    private double calculateStraightDistance(double lat1, double lng1, double lat2, double lng2) {
        double radLat1 = Math.toRadians(lat1);
        double radLat2 = Math.toRadians(lat2);
        double radLng1 = Math.toRadians(lng1);
        double radLng2 = Math.toRadians(lng2);
        
        double a = radLat1 - radLat2;
        double b = radLng1 - radLng2;
        
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        
        return s * 6371000; // 地球半径6371千米
    }
} 